package com.proyectofinal.ramas.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.proyectofinal.ramas.domain.Role;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service for processing Roles
 * 
 */
@Service("roleService")
@Transactional
public class RoleService {

	protected static Logger logger = Logger.getLogger("service");
	
	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;
	
	/**
	 * Retrieves all roles
	 * 
	 * @return a list of roles
	 */
	public List<Role> getAll() {
		logger.debug("Retrieving all roles");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Create a Hibernate query (HQL)
		Query query = session.createQuery("FROM  Role");
		
		// Retrieve all
		return  query.list();
	}
	
	/**
	 * Retrieves a single role
	 */
	public Role get( Integer roleID ) {
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Retrieve existing role first
		Role role = (Role) session.get(Role.class, roleID);
		
		return role;
	}
	/**
	 * Adds a new role
	 */
	public void add(Role role) {
		logger.debug("Adding new role");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Save
		session.save(role);
	}
	
	/**
	 * Deletes an existing role
	 * @param roleID the roleID of the existing role
	 */
	public void delete(Integer roleID) {
		logger.debug("Deleting existing role");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Retrieve existing role first
		Role role = (Role) session.get(Role.class, roleID);
		
		// Delete 
		session.delete(role);
	}
	
	/**
	 * Edits an existing role
	 */
	public void edit(Role role) {
		logger.debug("Editing existing role");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Retrieve existing role via roleID
		Role existingRole = (Role) session.get(Role.class, role.getRoleID());
		
		// Assign updated values to this role
		existingRole.setDescript(role.getDescript());
		

		// Save updates
		session.save(existingRole);
	}
}
